package com.pine.app.module.security.core.matcher;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author xiaoyuan
 * @create 2019/8/2 16:47
 **/
@Slf4j
public class OrRequestMatcher implements RequestMatcher {

    private final List<RequestMatcher> requestMatchers;

    public OrRequestMatcher() {
        requestMatchers = new ArrayList<>();
    }

    public OrRequestMatcher(List<RequestMatcher> requestMatchers) {
        Assert.notEmpty(requestMatchers, "requestMatchers must contain a value");
        if (requestMatchers.contains((Object) null)) {
            throw new IllegalArgumentException("requestMatchers cannot contain null values");
        } else {
            this.requestMatchers = requestMatchers;
        }
    }

    public OrRequestMatcher(RequestMatcher... requestMatchers) {
        this(Arrays.asList(requestMatchers));
    }

    public void addMatchers(List<RequestMatcher> requestMatchers){
        this.requestMatchers.addAll(requestMatchers);
    }
    public void addMatcher(RequestMatcher requestMatchers){
        this.requestMatchers.add(requestMatchers);
    }

    public boolean matches(HttpServletRequest request) {
        Iterator var2 = this.requestMatchers.iterator();

        RequestMatcher matcher;
        do {
            if (!var2.hasNext()) {
                log.debug("No matches found");
                return false;
            }
            matcher = (RequestMatcher) var2.next();
            if (log.isDebugEnabled()) {
                log.debug("Trying to match using " + matcher);
            }
        } while (!matcher.matches(request));

        log.debug("matched");
        return true;
    }

    public String toString() {
        return "OrRequestMatcher [requestMatchers=" + this.requestMatchers + "]";
    }
}
